package com.qyx.pmpucat.service.impl;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.core.query.QueryWrapper;
import com.qyx.pmpucat.common.errorcode.BaseErrorCode;
import com.qyx.pmpucat.common.exception.ClientException;
import com.qyx.pmpucat.dto.UserLoginDTO;
import com.qyx.pmpucat.dto.UserLoginResponseDTO;
import com.qyx.pmpucat.dto.UserListResponseDTO;
import com.qyx.pmpucat.dto.UserQueryDTO;
import com.qyx.pmpucat.dto.UserRegisterDTO;
import com.qyx.pmpucat.entity.User;
import com.qyx.pmpucat.mapper.UserMapper;
import com.qyx.pmpucat.service.UserService;
import com.qyx.pmpucat.util.PasswordEncoder;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

// 导入表定义常量类
import static com.qyx.pmpucat.entity.table.UserTableDef.USER;

/**
 * 用户服务实现
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl implements UserService {

    private final UserMapper userMapper;

    @Override
    public void register(UserRegisterDTO registerDTO) {
        // 检查用户名是否已存在
        User existUser = getByUsername(registerDTO.getUsername());
        if (existUser != null) {
            throw new ClientException(BaseErrorCode.USER_NAME_EXIST_ERROR);
        }

        // 创建新用户
        User user = new User();
        BeanUtils.copyProperties(registerDTO, user);
        
        // 加密密码
        user.setPassword(PasswordEncoder.encode(registerDTO.getPassword()));
        
        // 设置用户状态为正常
        user.setStatus(1);
        
        // 保存用户
        userMapper.insert(user);
    }

    @Override
    public UserLoginResponseDTO login(UserLoginDTO loginDTO) {
        // 根据用户名查询用户
        User user = getByUsername(loginDTO.getUsername());
        if (user == null) {
            throw new ClientException("用户名或密码错误");
        }

        // 判断用户状态
        if (user.getStatus() != 1) {
            throw new ClientException("账号已被禁用");
        }

        // 校验密码
        if (!PasswordEncoder.matches(loginDTO.getPassword(), user.getPassword())) {
            throw new ClientException("用户名或密码错误");
        }

        // 生成登录凭证
        StpUtil.login(user.getId());
        setUserSession(user);
        // 组装返回数据
        return UserLoginResponseDTO.builder()
                .userId(user.getId())
                .token(StpUtil.getTokenValue())
                .username(user.getUsername())
                .realName(user.getRealName())
                .phone(user.getPhone())
                .gender(user.getGender())
                .build();
    }
    
    private void setUserSession(User user) {
        SaSession session = StpUtil.getSession();
        session.set("user", user);
    }

    @Override
    public User getByUsername(String username) {
        QueryWrapper queryWrapper = QueryWrapper.create();
        queryWrapper.where(USER.USERNAME.eq(username));
        return userMapper.selectOneByQuery(queryWrapper);
    }
    
    @Override
    public User getById(Long id) {
        return userMapper.selectOneById(id);
    }

    @Override
    public Page<User> getUserPage(UserQueryDTO queryDTO) {
        // 构建查询条件
        QueryWrapper queryWrapper = QueryWrapper.create();

        // 真实姓名模糊查询
        if (StringUtils.hasText(queryDTO.getRealName())) {
            queryWrapper.and(USER.REAL_NAME.like("%" + queryDTO.getRealName() + "%"));
        }

        // 城市查询
        if (StringUtils.hasText(queryDTO.getCity())) {
            queryWrapper.and(USER.CITY.eq(queryDTO.getCity()));
        }

        // 年龄查询
        if (queryDTO.getAge() != null) {
            queryWrapper.and(USER.AGE.eq(queryDTO.getAge()));
        }

        // 手机号模糊查询
        if (StringUtils.hasText(queryDTO.getPhone())) {
            queryWrapper.and(USER.PHONE.like("%" + queryDTO.getPhone() + "%"));
        }

        // 性别查询
        if (queryDTO.getGender() != null) {
            queryWrapper.and(USER.GENDER.eq(queryDTO.getGender()));
        }

        // 按创建时间倒序排序
        queryWrapper.orderBy(USER.CREATE_TIME.desc());

        // 分页查询
       return userMapper.paginate(queryDTO.getPageNum(), queryDTO.getPageSize(), queryWrapper);
    }

    @Override
    public Map<Long, User> mapUserByUserIds(Set<Long> userIds) {
        if (CollUtil.isEmpty(userIds)){
            return Collections.emptyMap();
        }
      return   userMapper.selectListByQuery(QueryWrapper.create().where(USER.ID.in(userIds)))
                .stream().collect(Collectors.toMap(User::getId, Function.identity()));
    }
} 